package com.zhongli.devplatform.utils.im;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author WuXiCheng
 * @version 1.0
 */
public class RequestUtil {

	/**
	 * 从request中获取key的参数值并转换类型
	 * @param request
	 * @param key
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T extends Number> T getNumber(HttpServletRequest request, String key, Class<T> clazz){

		String value = request.getParameter(key);
		if (value == null || value.equals("")) {
			return null;
		}

		try {
			Constructor<T> constructor = clazz.getConstructor(String.class);
//			constructor.setAccessible(true);		// new T(String) 都是public
			return constructor.newInstance(value);

		} catch (NoSuchMethodException e) {
			throw new RuntimeException("不支持的类型:" + clazz);
		} catch (IllegalAccessException e) {
			throw new RuntimeException("私有的构造函数:" + clazz);
		} catch (InstantiationException e) {
			throw new RuntimeException("不匹配的数值类型:" + value + "  --->  " + clazz);
		} catch (InvocationTargetException e) {
			throw new RuntimeException("实例化失败:" + clazz + "\tValue:" + value);
		}

	}

	public static Long getLong(HttpServletRequest request, String key){
		return getNumber(request, key, Long.class);

	}

	public static Integer getInteger(HttpServletRequest request, String key) {
		return getNumber(request, key, Integer.class);
	}

	public static Boolean getBoolean(HttpServletRequest request, String key) {
		String value = request.getParameter(key);
		if (value == null) {
			return false;
		}
		return Boolean.valueOf(value);
	}
}
